<template>
  <div>
    <BasicModal
      @register="registerModal"
      v-bind="$attrs"
      ok-text="保存"
      @ok="handleSubmit"
      :closeFunc="handleClose"
      :show-cancel-btn="hasPermission(RoleEnum.TENANT_ADMIN)"
      :show-ok-btn="hasPermission(RoleEnum.TENANT_ADMIN)"
    >
      <Tabs v-model:activeKey="activeKey" @change="handleChange">
        <TabPane
          :disabled="hasPermission(RoleEnum.TENANT_ADMIN)"
          v-for="item in tabsFormList"
          :key="item.key"
          v-bind="omit(item, ['Form', 'key'])"
          :forceRender="true"
        >
          <BasicForm @register="item.Form[0]" />
        </TabPane>
      </Tabs>
    </BasicModal>
  </div>
</template>

<script setup lang="ts">
  import { defineEmits, reactive, ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm } from '/@/components/Form';
  import { Tabs, TabPane } from 'ant-design-vue';
  import { omit } from 'lodash-es';
  import { tabsFormList } from './credentialsModal.data';
  import { getCredentials } from '/@/api/thingsborad/entity/entity';
  import { deviceCredentialsInfo } from '/@/api/thingsborad/entity/model/entityModel';
  import { modalStyleSetting } from '/@/settings/thingsBoardDesign';
  import { RoleEnum } from '/@/enums/roleEnum';
  import { usePermission } from '/@/hooks/web/usePermission';
  const { hasPermission } = usePermission();
  const emit = defineEmits(['success', 'register']);
  let key = ref('');
  let activeKey = ref('ACCESS_TOKEN');
  let tabsList = reactive(tabsFormList);
  let credentialsResponse: deviceCredentialsInfo;
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ loading: true, confirmLoading: true, ...modalStyleSetting });
    let params = data?.record?.id + '/credentials';
    credentialsResponse = await getCredentials(params);
    activeKey.value = credentialsResponse.credentialsType;
    tabsList.forEach((item) => {
      if (item.key == credentialsResponse.credentialsType) {
        const { setFieldsValue } = item.Form[1];
        setFieldsValue({
          token: credentialsResponse.credentialsId,
        });
        switch (credentialsResponse.credentialsType) {
          case 'ACCESS_TOKEN':
            setFieldsValue({ token: credentialsResponse.credentialsId });
            break;
          case 'X509_CERTIFICATE':
            setFieldsValue({ certificate: credentialsResponse.credentialsValue });
            break;
          case 'MQTT_BASIC':
            setFieldsValue({
              id: JSON.parse(credentialsResponse.credentialsValue).clientId,
              username: JSON.parse(credentialsResponse.credentialsValue).userName,
              password: JSON.parse(credentialsResponse.credentialsValue).password,
            });
            break;
        }
      }
    });
    key.value = data?.key;
    setModalProps({
      title: '设备凭据',
    });
    setModalProps({ loading: false, confirmLoading: false });
  });

  function handleSubmit() {
    tabsList.forEach(async (item) => {
      if (item.key == activeKey.value) {
        const { validate, resetFields } = item.Form[1];
        const value = await validate();
        setModalProps({ confirmLoading: true });
        closeModal();
        resetFields();
        emit('success', {
          key: 'credentials',
          credentialsType: activeKey.value,
          value,
          credentialsResponse,
        });
        setModalProps({ confirmLoading: false });
      }
    });
  }

  async function handleClose() {
    for (const item of tabsList) {
      const { resetFields } = item.Form[1];
      resetFields();
    }
    return true;
  }
  function handleChange() {
    for (const item of tabsList) {
      const { resetFields } = item.Form[1];
      resetFields();
    }
  }
</script>
